<template>
  <div class="cg-multiple-select">
    <div class="cg-multiple-select-row" v-for="(value, index) in data" :key="index">
      <cg-select
        :value="value"
        @change="(v) => handleSelect(v, index)"
        :options="options"
      ></cg-select>
      <cg-button @click="addItem">+</cg-button>
      <cg-button @click="() => removeItem(index)">-</cg-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

// 定义组件名称
defineOptions({
  name: 'cg-multiple-select'
})

// 定义props
const props = withDefaults(
  defineProps<{
    modelValue: string
    sep: string
    placeholder: string
    options: Array<{
      value: string | number
      label: string
    }>
  }>(),
  {
    sep: ',',
    placeholder: '请选择',
    options: () => []
  }
)

// 定义emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: Array<string | number>): void
}>()

// 响应式数据
const data = ref<Array<string | number>>([])

// 监听modelValue变化
watch(
  () => props.modelValue,
  (val) => {
    data.value = stringToArray(val)
  },
  { immediate: true }
)

// 监听data变化并触发事件
watch(
  data,
  (newVal) => {
    const strValue = arrayToString(newVal)
    emit('update:modelValue', strValue)
    emit('change', newVal)
  },
  { deep: true }
)

// 辅助方法
const stringToArray = (str: string): Array<string | number> => {
  if (!str) return []
  return str.split(props.sep).map((item) => {
    // 尝试转换为数字
    const num = Number(item)
    return isNaN(num) ? item.trim() : num
  })
}

const arrayToString = (arr: Array<string | number>): string => {
  return arr.join(props.sep)
}

const handleSelect = (value: string | number, index: number) => {
  console.log('handleSelect', value, index)
  // 创建新数组以触发响应式更新
  const newData = [...data.value]
  newData[index] = value
  data.value = newData
}

const addItem = () => {
  // 添加一个新的空选项
  data.value = [...data.value, '']
}

const removeItem = (index: number) => {
  // 移除指定索引的选项
  if (data.value.length > 1) {
    const newData = [...data.value]
    newData.splice(index, 1)
    data.value = newData
  } else {
    console.warn('至少保留一个选项')
  }
}
</script>

<style lang="scss">
.cg-multiple-select {
  .cg-multiple-select-row {
    display: flex;
    margin-bottom: 10px;

    .cg-select {
      flex: 1;
    }

    .cg-button {
      margin-left: 5px;
    }
  }
}
</style>
